<template>
	<div class="video-chat-container">
		<!-- 通话中界面 -->
		<div class="video-container" v-if="isInCall" id="videoCall">
			<!-- 远程视频 -->
			<video class="remote-video" id="remoteVideo" autoplay playsinline></video>

			<!-- 本地视频 -->
			<video class="local-video" id="localVideo" autoplay playsinline muted></video>

			<div class="call-info">
				<div class="caller-name">{{ contactInfo.contactName }}</div>
				<div class="call-status">{{ callDuration }}</div>
			</div>

			<div class="control-buttons">
				<button class="control-button mute" id="muteBtn" @click="toggleMute">
					<img class="fa" :src="isMuted ? '/static/images/microphone-slash.svg' : '/static/images/microphone.svg'"
						alt="" />
					<span>{{ isMuted ? '取消静音' : '静音' }}</span>
				</button>
				<button class="control-button speaker" id="speakerBtn" @click="toggleSpeaker">
					<img class="fa" :src="isSpeakerOn ? '/static/images/volume-up.svg' : '/static/images/volume-off.svg'"
						alt="" />
					<span>{{ isSpeakerOn ? '关闭扬声器' : '扬声器' }}</span>
				</button>
				<button class="control-button switch-camera" id="changeBtn" @click="switchCamera">
					<img class="fa" src="/static/images/camera-retro.svg" alt="" />
					<span>切换</span>
				</button>
				<button class="control-button end-call" id="endCallBtn" @click="endCall">
					<img class="fa" src="/static/images/phone-slash.svg" alt="" />
					<span>挂断</span>
				</button>
			</div>
		</div>

		<!-- 来电界面 -->
		<div v-if="showIncomingCall" id="incoming-call">
			<div class="incoming-call">
				<img :src="contactInfo.contactAvatar" alt="头像" class="caller-avatar">
				<div class="caller-name">{{ contactInfo.contactName }}</div>
				<div class="call-status">视频通话邀请...</div>

				<div class="answer-buttons">
					<div class="decline-call" id="declineCallBtn" @click="declineCall">
						<img class="fa" src="/static/images/phone-slash.svg" alt="" />
					</div>
					<div class="accept-call" id="acceptCallBtn" @click="acceptCall" v-if="!isSelf">
						<img class="fa" src="/static/images/phone.svg" alt="" />
					</div>
				</div>
			</div>
		</div>

		<!-- 加载指示器 -->
		<div class="loading" v-if="isLoading">{{ loadingMessage }}</div>

		<!-- toast提示 -->
		<div id="toast" class="toast" :class="{ hide: !showToast, show: showToast }">
			<div class="toast-content">
				<p>{{ toastMessage }}</p>
			</div>
		</div>
	</div>
</template>

<script>

	export default {
		name: 'VideoChat',
		props: {
			channelInfo: {
				type: Object,
				required: true
			},
			userInfo: {
				type: Object,
				required: true
			},
			contactInfo: {
				type: Object,
				required: true
			},
			isSelf: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				isInCall: false,
				showIncomingCall: true,
				isLoading: false,
				loadingMessage: '正在连接...',
				showToast: false,
				toastMessage: '',
				callDuration: '00:00:00',
				isMuted: false,
				isSpeakerOn: false,
				callTimer: null,
				seconds: 0,
				client: null,
				localVideoTrack: null,
				localAudioTrack: null,
				remoteUid: null,
				params: {},
			};
		},
		created() {
			this.playRingtone();
		},
		beforeUnmount() {
			this.cleanup();
		},
		methods: {
			playRingtone() {
				console.log("播放来电铃声...");
			},
			async acceptCall() {
				await this.joinChannel();
			},
			declineCall() {
				this.showIncomingCall = false;
				console.log("已拒绝视频通话");
				this.$emit('call-action', {
					callerId: "caller",
					status: false,
					timestamp: Date.now(),
					userId: this.userInfo.id,
					type: 'voice'
				});
				this.leaveChannel()
			},
			endCall() {
				this.handeUp(this.userInfo.id);
			},
			toggleMute() {
				this.isMuted = !this.isMuted;
				if (this.localAudioTrack) {
					if (this.isMuted) {
						this.localAudioTrack.setVolume(0);
					} else {
						this.localAudioTrack.setVolume(this.isSpeakerOn ? 100 : 50);
					}
				}
			},
			toggleSpeaker() {
				this.isSpeakerOn = !this.isSpeakerOn;
				if (this.localAudioTrack) {
					this.localAudioTrack.setVolume(this.isSpeakerOn ? 100 : 50);
				}
			},
			switchCamera() {
				// Implement camera switching logic
				console.log("切换摄像头");
			},
			handeUp(userUid) {
				this.isInCall = false;
				console.log("视频通话已结束");
				this.$emit('call-action', {
					callerId: "handelUp",
					status: false,
					timestamp: Date.now(),
					userId: userUid,
					type: 'voice'
				});
				this.stopCallTimer();
				this.leaveChannel();
			},
			accetp(userUid) {
				this.$emit('call-action', {
					callerId: "caller",
					status: true,
					timestamp: Date.now(),
					userId: userUid,
					type: 'voice'
				});
			},
			startCallTimer() {
				this.seconds = 0;
				this.callTimer = setInterval(() => {
					this.seconds++;
					const hours = Math.floor(this.seconds / 3600);
					const minutes = Math.floor((this.seconds % 3600) / 60);
					const secs = this.seconds % 60;
					this.callDuration =
						`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
				}, 1000);
			},
			stopCallTimer() {
				if (this.callTimer) {
					clearInterval(this.callTimer);
					this.callTimer = null;
				}
			},
			sendToUniApp(message) {
				console.log("向外层发送消息:", message);
				if (window.uni?.postMessage) {
					uni.postMessage({
						data: message
					});
					return;
				}
				if (window.parent !== window) {
					window.parent.postMessage({
						type: 'webview',
						data: message
					}, '*');
				}
			},
			async joinChannel() {
				const {
					appId,
					channel,
					token
				} = this.channelInfo;
				const userId = this.userInfo.id;

				if (!appId || !channel) {
					console.log("App ID 和频道名不能为空");
					return;
				}

				try {
					this.showLoading("正在连接...");
					const devices = await AgoraRTC.getMicrophones();
					if (devices.length === 0) {
						console.log('未找到麦克风设备');
						this.handleJoinError(userId, '未找到麦克风设备');
						return;
					}

					AgoraRTC.setLogLevel(2);
					this.client = AgoraRTC.createClient({
						mode: "rtc",
						codec: "vp8"
					});

					const uid = await this.client.join(appId, channel, token || null, userId);
					console.log('本地用户ID', uid);
					if(this.isSelf){ // 谁发起就谁先发布流
						await this.publishLocalTracks();
					}
					this.setupClientEvents();
				} catch (error) {
					console.log(`加入频道失败: ${error.message}`);
					this.stopCallTimer();
					this.handleJoinError(userId, '连接失败');
				}
			},
			setupClientEvents() {
				this.client.on("user-joined", async (user) => {
					console.log(`用户 ${user.uid} 加入了频道`);
					this.remoteUid = user.uid;
					this.addUserToUI(user.uid);
					await this.publishLocalTracks();
				});

				this.client.on("user-published", async (user, mediaType) => {
					console.log(`用户 ${user.uid} 发布了 ${mediaType} 流`);
					await this.client.subscribe(user, mediaType);

					if (mediaType === "video") {
						const remoteVideoTrack = user.videoTrack;
						const remoteVideo = document.getElementById('remoteVideo');
						remoteVideo.srcObject = new MediaStream([remoteVideoTrack.getMediaStreamTrack()]);

						remoteVideoTrack.on("track-ended", () => {
							console.log(`用户 ${user.uid} 视频已结束`);
							remoteVideo.srcObject = null;
						});
					}

					if (mediaType === "audio") {
						const remoteAudioTrack = user.audioTrack;
						remoteAudioTrack.play();
						// 远程用户发布在显示通话页面
						this.showIncomingCall = false;
						this.isInCall = true;
						
						this.client.enableAudioVolumeIndicator();
						this.client.on("volume-indicator", (volumes) => {
							volumes.forEach(volume => {
								if (volume.uid === user.uid) {
									// updateSpeakingIndicator(volume.level > 5);
								}
							});
						});
						remoteAudioTrack.on("track-ended", () => {
							console.log(`用户 ${user.uid} 音频已结束`);
						});
					}
				});

				this.client.on("user-unpublished", (user, mediaType) => {
					console.log(`用户 ${user.uid} 取消发布了 ${mediaType} 流`);
					if (mediaType === "video") {
						const remoteVideo = document.getElementById('remoteVideo');
						remoteVideo.srcObject = null;
						this.remoteUid = null;
					}
					this.handeUp(user.uid);
				});

				this.client.on("user-left", (user) => {
					console.log(`用户 ${user.uid} 离开了频道`);
					if (user.uid === this.remoteUid) {
						const remoteVideo = document.getElementById('remoteVideo');
						remoteVideo.srcObject = null;
						this.remoteUid = null;
					}
					this.handeUp(user.uid);
				});

				this.client.on("network-quality", (stats) => {
					this.updateNetworkStatus(stats);
				});

				this.client.on("connection-state-change", (state, reason) => {
					console.log(`连接状态变化: ${state}, 原因: ${reason}`);
					if (state === "DISCONNECTED") {
						this.handeUp(this.userInfo.id);
					}
				});
			},
			async publishLocalTracks() {
				try {
					[this.localAudioTrack, this.localVideoTrack] = await AgoraRTC.createMicrophoneAndCameraTracks({
						encoderConfig: "speech_standard",
						AEC: true,
						ANS: true
					}, {
						encoderConfig: "720p_1",
						facingMode: "user"
					});

					const localVideo = document.getElementById('localVideo');
					localVideo.srcObject = new MediaStream([this.localVideoTrack.getMediaStreamTrack()]);

					await this.client.publish([this.localAudioTrack, this.localVideoTrack]);
					console.log("本地音视频发布成功");

					this.localAudioTrack.on("volume-change", (volume) => {
						if (volume === 0 && !this.isMuted) {
							this.isMuted = true;
						}
					});

					this.startCallTimer();
					this.hideLoading();
				} catch (error) {
					console.error("发布本地轨道失败:", error);

					try {
						this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack({
							encoderConfig: "speech_standard",
							AEC: true,
							ANS: true
						});

						await this.client.publish([this.localAudioTrack]);
						console.log("本地音频发布成功");
						this.showToast("摄像头不可用");

						this.showIncomingCall = false;
						this.isInCall = true;
						this.startCallTimer();
						this.hideLoading();
					} catch (audioError) {
						console.error("发布本地音频失败:", audioError);
						this.handlePublishError(this.userInfo.id, '麦克风不可用');
						throw audioError;
					}
				}
			},
			async unpublishLocalTracks() {
				try {
					if (this.client) {
						if (this.localAudioTrack) {
							await this.client.unpublish([this.localAudioTrack]);
							this.localAudioTrack.close();
							this.localAudioTrack = null;
						}

						if (this.localVideoTrack) {
							await this.client.unpublish([this.localVideoTrack]);
							this.localVideoTrack.close();
							this.localVideoTrack = null;
						}
					}
				} catch (error) {
					console.error("取消发布本地轨道失败:", error);
				}
			},
			async leaveChannel() {
				if (!this.client) {
					console.log("客户端未初始化");
					return;
				}
				try {
					await this.unpublishLocalTracks();
					await this.client.leave();
					this.client = null;
					console.log("成功离开频道");
				} catch (error) {
					console.error("离开频道失败:", error);
					this.forceCleanup();
					throw error;
				} finally {
					const localVideo = document.getElementById('localVideo');
					const remoteVideo = document.getElementById('remoteVideo');
					localVideo.srcObject = null;
					remoteVideo.srcObject = null;
				}
			},
			forceCleanup() {
				this.unpublishLocalTracks();
				if (this.client) {
					try {
						this.client.leave();
					} catch (e) {
						console.warn("强制离开频道时出错:", e);
					}
					this.client = null;
				}
			},
			cleanup() {
				this.stopCallTimer();
				this.leaveChannel();
			},
			handleJoinError(userId, error) {
				this.$emit('call-action', {
					callerId: "audioCall",
					status: false,
					timestamp: Date.now(),
					userId: this.userInfo.id,
					error: error
				});
			},
			handlePublishError(userId, error) {
				this.$emit('call-action', {
					callerId: "audioCall",
					status: false,
					timestamp: Date.now(),
					userId: this.userInfo.id,
					error: error
				});
			},
			addUserToUI(uid) {
				console.log(`用户 ${uid} 加入UI`);
			},
			updateNetworkStatus(stats) {
				if (stats.downlinkNetworkQuality > 4) {
					this.showToast('网络较差');
				}
				if (stats.downlinkNetworkQuality > 6) {
					this.showToast('网络非常差');
				}
			},
			showLoading(message) {
				this.loadingMessage = message;
				this.isLoading = true;
			},
			hideLoading() {
				this.isLoading = false;
			},
			showToast(message) {
				this.toastMessage = message;
				setTimeout(() => {
					uni.showToast({
						title: message,
						icon: 'none'
					})
				}, 1000);
			}
		}
	};
</script>

<style scoped>
	/* 保持原有的CSS样式，这里只展示部分关键样式 */
	.video-chat-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #1a1a1a;
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.video-container {
		position: relative;
		width: 100%;
		height: 100%;
		background-color: #000;
	}

	.remote-video {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.local-video {
		position: absolute;
		width: 120px;
		height: 160px;
		right: 10px;
		top: 10px;
		border-radius: 8px;
		object-fit: cover;
	}

	.call-info {
		position: absolute;
		top: 20px;
		left: 0;
		right: 0;
		text-align: center;
		color: white;
		z-index: 10;
	}

	.control-buttons {
		position: absolute;
		bottom: 30px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 20px;
		z-index: 10;
	}

	.control-button {
		background: rgba(255, 255, 255, 0.2);
		border: none;
		border-radius: 50%;
		width: 60px;
		height: 60px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: white;
		cursor: pointer;
	}

	.control-button img {
		width: 24px;
		height: 24px;
		margin-bottom: 5px;
		filter: brightness(0) invert(1);
	}

	.control-button.end-call {
		background: #ff3b30;
	}

	/* 来电振动动画 */
	@keyframes vibrate {
		0% {
			transform: rotate(0deg);
		}

		25% {
			transform: rotate(2deg);
		}

		50% {
			transform: rotate(0deg);
		}

		75% {
			transform: rotate(-2deg);
		}

		100% {
			transform: rotate(0deg);
		}
	}

	.incoming-call {
		animation: vibrate 0.3s infinite;
		text-align: center;
	}

	#incoming-call {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #1a1a1a;
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.caller-avatar {
		width: 120px;
		height: 120px;
		border-radius: 60px;
		margin-bottom: 20px;
	}

	.answer-buttons {
		display: flex;
		gap: 40px;
		margin-top: 40px;
	}

	.decline-call,
	.accept-call {
		width: 60px;
		height: 60px;
		border-radius: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}
	.decline-call img,
	.accept-call img {
		width: 30px;
		height: 30px;
		filter: brightness(0) invert(1);
	}

	.decline-call {
		background: #ff3b30;
	}

	.accept-call {
		background: #34c759;
	}

	.loading {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		z-index: 30;
	}

	.toast {
		position: fixed;
		bottom: 100px;
		left: 50%;
		transform: translateX(-50%);
		background: rgba(0, 0, 0, 0.7);
		color: white;
		padding: 10px 20px;
		border-radius: 20px;
		z-index: 40;
		opacity: 0;
		transition: opacity 0.3s;
	}

	.toast.show {
		opacity: 1;
	}

	.toast.hide {
		opacity: 0;
	}
</style>